// miniprogram/pages/my/publish/publish.js
var db=wx.cloud.database();
var app=getApp();
const util = require('../../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    havePicture:false,
    tempFilepath:"",
    title:"",
    detail:"",
    expectedPrice:"",
    fileID:""



  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  chooseImg: function(){
    var that=this
    wx.chooseImage({
      count: 1,
      sizeType:["original","compressed"],
      success:function(res){
        var tempFilePaths = res.tempFilePaths
        that.setData({
          havePicture:true,
          tempFilepath:tempFilePaths[0]
        })

      }
    })

  },
  test:function(){
    console.log("test publishing")
    this.setData({
      title:"This is an upload test",
      expectedPrice:10,
      detail:"This is information",
      
    })
    this.uploadPic()
  },
  uploadPic(){
    //var that=this
    
    if(this.data.havePicture){
      console.log(this.data.havePicture)
      wx.cloud.uploadFile({
        cloudPath: 'fleaMarketPic/'+this.data.title+".jpg",
        filePath: this.data.tempFilepath,
      // 成功回调
      success:res=> {
        console.log(res)
        this.setData({
          fileID:res.fileID
        })
        this.publish()

        //console.log(res.errMsg=="cloud.uploadFile:ok")
        
        if(res.errMsg=="cloud.uploadFile:ok"){
          this.publish()
        
        }else{
          wx.showToast({
            title: '出现问题，请重试',
          })
        }
      
      },
    
      })
      
    }else{
      this.publish()
    }
    
    

  },
  publish(){
    db.collection('publishInfo').add({
      data:{
      title:this.data.title,
      detail:this.data.detail,
      expectedPrice:this.data.expectedPrice,
      nickName:getApp().globalData.nickName,
      havePicture:this.data.havePicture,
      tempFilePath:this.data.fileID,
    
      time:util.formatTime(new Date())
    }
    }).then(res=>{
      wx.navigateBack({
        delta: 0,
      })
    })

  }

})